<template>
  <el-scrollbar v-loading="loading" class="excel-file">
    <template v-if="!loading">
      <el-table v-if="tableData.length > 0" :data="tableData" style="width: 100%;" border>
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.label"
          :label="item.label"
          :width="item.width"
        ></el-table-column>
      </el-table>

      <el-empty v-else-if="tableData.length === 0" class="no-data" description="暂无数据"></el-empty>
    </template>
  </el-scrollbar>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'excel-file',
  props: ['file', 'loading'],
  data() {
    return {
      tableData: [],
      tableColumns: [],
    };
  },
  watch: {
    file: {
      handler(val) {
        if (val) {
          this.getArrayBuffer(val);
        }
      },
      immediate: true,
    },
  },
  methods: {
    getArrayBuffer(fileData) {
      // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
      const workbook = XLSX.read(new Uint8Array(fileData), { type: 'array' });
      const sheetNames = workbook.SheetNames; // 工作表名称集合
      const worksheet = workbook.Sheets[sheetNames[0]];
      const excelData = XLSX.utils.sheet_to_json(worksheet);

      if (excelData && excelData.length > 0) {
        const current = [];
        Object.keys(excelData[0]).forEach(key => {
          current.push({
            label: key,
            value: excelData[0][key],
            width: '180',
          });
        });
        this.tableColumns = current;
        this.tableData = excelData;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.excel-file {
  width: 100%;
  height: 100%;
  padding-right: 8px;
  position: relative;

  .no-data {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
